package com.vitabuybuy.tv.ui.auth

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.core.os.bundleOf
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.TimePickerView
import com.blankj.utilcode.util.TimeUtils
import com.luck.picture.lib.PictureSelector
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityPersonalInformationBinding
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.vitabuybuy.tv.dto.RegionDto
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.NetUrl
import com.library.common.toast.XToast
import com.library.common.util.PictureUtils
import com.vitabuybuy.tv.ui.auth.viewmodel.AuthViewModel
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_personal_information.*
import java.text.SimpleDateFormat
import java.util.*

class PersonalInformationActivity :
    BaseActivity<AuthViewModel, ActivityPersonalInformationBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_personal_information

    private val REQUEST_CODE_CAMMER = 10003

    private var countryCode: String? = ""
    private var phone: String? = ""
    private var password: String? = ""
    private var regionId = -1
    private val picDialog by lazy { OptionsDialog(mContext) }
    private val genderDialog by lazy { OptionsDialog(mContext) }

    private var areaDialog: BottomDialog? = null
    private lateinit var timePickerView: TimePickerView

    override fun onGetBundle(bundle: Bundle?) {
        countryCode = bundle?.getString("countryCode")
        phone = bundle?.getString("phone")
        password = bundle?.getString("password")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.personal_info))
//        mTvRight.apply {
//            text = getString(R.string.skip)
//            visibility = View.VISIBLE
//            setOnClickListener{
//
//            }
//        }
    }

    override fun observeData() {
        viewModel.imageUrl.observe(this, androidx.lifecycle.Observer {
            mBinding.avatarUrl = NetUrl.FILE_PROFILE.plus(it)
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(ivAvatar, btnNext, tvBirthday, tvAddress, rlSex){v->
            when (v) {
                ivAvatar -> {
                    AndPermission.with(this)
                        .runtime()
                        .permission(Permission.Group.CAMERA, Permission.Group.STORAGE)
                        .onDenied {
                            if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                                // 这些权限被用户总是拒绝。
                                XToast.normal(getString(R.string.request_necessary_permissions))
                            }
                        }
                        .onGranted {
                            picDialog.show()
                        }.start()
                }
                tvBirthday -> {
                    timePickerView.apply {
                        setDate(Calendar.getInstance())
                        show(tvBirthday)
                    }
                }
                rlSex -> {
                    genderDialog.setBtnStr(getString(R.string.male), getString(R.string.female))
                    genderDialog.show()
                }
                tvAddress -> {
                    //这里一定要重新创建
                    areaDialog = BottomDialog(this, 5)
                    viewModel.getRegionList(null)
                }
                btnNext -> {
//                if (mBinding.avatarUrl.isNullOrEmpty()) {
//                    XToast.normal(getString(R.string.please_upload_avatar))
//                    return
//                }
                    if (etUsername.text.isEmpty()) {
                        XToast.normal(getString(R.string.please_input_nickname))
                        return@setOnclickNoRepeat
                    }
                    if (etUsername.text.toString().length < 4) {
                        XToast.normal(getString(R.string.nickname_dialog_tip))
                        return@setOnclickNoRepeat
                    }
                    if (spnChoose.text.isEmpty()) {
                        XToast.normal(getString(R.string.please_choose_sex))
                        return@setOnclickNoRepeat
                    }
                    if (tvBirthday.text.isEmpty()) {
                        XToast.normal(getString(R.string.please_choose_birthday))
                        return@setOnclickNoRepeat
                    }
                    if (tvAddress.text.isEmpty()) {
                        XToast.normal(getString(R.string.please_choose_address))
                        return@setOnclickNoRepeat
                    }
                    BindEmailActivity.openActivity(
                        mContext, bundleOf(
                            Pair("countryCode", countryCode),
                            Pair("phone", phone),
                            Pair("password", password),
                            Pair("avatar", mBinding.avatarUrl ?: ""),
                            Pair("nickname", etUsername.text.toString()),
                            Pair("gender", spnChoose.text.toString()),
                            Pair("birthday", tvBirthday.text.toString()),
                            Pair("regionId", regionId),
                            Pair("from", BindEmailActivity.FROM_REGISTER)
                        )
                    )
                }
            }
        }
        picDialog.onTwoClick = {
            PictureUtils.openAluamOneRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        picDialog.onOneClick = {
            PictureUtils.openCameraRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        genderDialog.onTwoClick = {
            spnChoose.text = getString(R.string.female)
        }
        genderDialog.onOneClick = {
            spnChoose.text = getString(R.string.male)
        }

        timePickerView = TimePickerBuilder(this) { date, v -> //选中事件回调
            (v as TextView).text =
                TimeUtils.date2String(date, SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
        }.setType(booleanArrayOf(true, true, true, false, false, false)) // 默认全部显示
            .setCancelText(getString(R.string.cancel)) // 取消按钮文字
            .setSubmitText(getString(R.string.confirm)) // 确认按钮文字
            .setContentTextSize(16) // 滚轮文字大小
            .setTitleSize(16) // 标题文字大小
            .setTitleText(getString(R.string.choose_time)) // 标题文字
            .setOutSideCancelable(true) // 点击屏幕，点在控件外部范围时，是否取消显示
            .isCyclic(true) // 是否循环滚动
            .setTitleColor(Color.parseColor("#323233")) // 标题文字颜色
            .setTitleBgColor(Color.WHITE) // 标题背景颜色
            .setBgColor(Color.WHITE) // 滚轮背景颜色
            .setDividerColor(Color.parseColor("#DCDDE0"))
            .setOutSideColor(Color.TRANSPARENT)
            .setSubCalSize(14)
            .setSubmitColor(Color.parseColor("#E23225"))
            .setCancelColor(Color.parseColor("#E23225"))
            .setItemVisibleCount(7)
            .build()
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            9 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                            selectAbles?.run {
                                var area = ""
                                for (selectAble in this) {
                                    area = area + selectAble.name + "  "
                                    regionId = selectAble.id
                                }
                                mBinding.tvAddress.text = area
                                areaDialog = null
                            }
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            viewModel.getRegionList(selectAble?.id)
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_CAMMER -> {
                    val path = PictureSelector.obtainMultipleResult(data)[0].cutPath
                    viewModel.uploadImage(path)
                }
            }
        }
    }

    companion object {
        fun openActivity(
            mContext: BaseActivity<*, *>,
            countryCode: String?,
            phone: String?,
            password: String
        ) {
            val bundle = Bundle();
            bundle.putString("countryCode", countryCode)
            bundle.putString("phone", phone)
            bundle.putString("password", password)
            mContext.startActivity(bundle, PersonalInformationActivity::class.java)
        }
    }
}
